import React, { Component } from 'react'

class TodoList extends Component {
    constructor (props) {
        super (props)
        this.handleChange = this.handleChange.bind(this)
        this.handleClickSubmit = this.handleClickSubmit.bind(this)
        this.handleClickRemove = this.handleClickRemove.bind(this)
        this.state = {
            inputValue: '',
            list: []
        }
    }
    handleChange (e) {
        let val = e.target.value
        this.setState ((prevState) => ({
            inputValue: val
        }))
    }
    handleClickSubmit () {
        this.setState((prevState) => {
            let list = [...prevState.list];
            list = [prevState.inputValue, ...list]
            return {
                list,
                inputValue: ''
            }
        })
    }
    handleClickRemove (index) {
        this.setState ((prevState) => {
            let list = prevState.list
            list.splice(index, 1)
            return {
                list
            }
        })
    }
    render () {
        return (
            <div>
                <input onChange = {this.handleChange} value = {this.state.inputValue} type="text" placeholder="请输入" />
                <button onClick = {this.handleClickSubmit}>提交</button>
                <ul>
                    {this.getList()}
                </ul>
                {!this.state.list.length && '赞无诗句'} 
            </div>
        )
    }
    getList () {
        return this.state.list.map((item,index) => {
            return (
                <li onClick={() => this.handleClickRemove(index)} key={index}>{item}</li>
            )
        })
    }
}

export default TodoList

